﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PMIS.Models;
using PMIS.Shared.Models;

namespace PMIS.HttpRequest
{
    public class HttpService
    {
        private readonly HttpClient _client;

        private readonly string baseUrl = "https://localhost:5001/";

        public HttpService()
        {
            _client = new HttpClient { BaseAddress = new Uri(baseUrl) };
        }

        public async Task<ApiResult?> GetAsync(string url, Dictionary<string, object>? parameters = null)
        {
            return await ExecuteAsync(url, parameters, HttpMethod.Get);
        }

        public async Task<ApiResult?> DeleteAsync(string url, Dictionary<string, object> parameters)
        {
            return await ExecuteAsync(url, parameters, HttpMethod.Delete);
        }

        public async Task<ApiResult?> PostAsync(string url, object parameters)
        {
            return await ExecuteAsync(url, parameters, HttpMethod.Post);
        }

        public async Task<ApiResult?> PutAsync(string url, object parameters)
        {
            return await ExecuteAsync(url, parameters, HttpMethod.Put);
        }

        private async Task<ApiResult?> ExecuteAsync(string url, object? parameters, HttpMethod method)
        {
            var bearerToken = AccountInfo.Instance.Token;
            var request = new HttpRequestMessage(method, url);

            request.Headers.Add("TenantId", "0");

            if (bearerToken != null)
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
            }

            if (method == HttpMethod.Post || method == HttpMethod.Put)
            {
                if (parameters != null)
                {
                    var json = JsonConvert.SerializeObject(parameters);
                    request.Content = new StringContent(json, Encoding.UTF8, "application/json");
                }
            }
            else
            {
                if (parameters is Dictionary<string, object> queryParameters)
                {
                    var queryString = string.Join("&", queryParameters.Select(kvp => $"{kvp.Key}={Uri.EscapeDataString(kvp.Value?.ToString() ?? string.Empty)}"));
                    request.RequestUri = new Uri($"{url}?{queryString}", UriKind.Relative);
                }
            }

            try
            {
                var response = await _client.SendAsync(request);
                var content = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    return JsonConvert.DeserializeObject<ApiResult?>(content);
                }
                else
                {
                    return new ApiResult
                    {
                        code = (int)response.StatusCode,
                        msg = response.ReasonPhrase,
                        data = null
                    };
                }
            }
            catch (Exception ex) 
            {
                int code = -1;
                if (ex is HttpRequestException e)
                {
                    if (e.StatusCode != null)
                    {
                        code = (int)e.StatusCode;
                    }
                }
                return new ApiResult
                {
                    code = code,
                    msg = ex.Message,
                };
            }
        }
    }
}
